package com.asia5b.a5mall.middleware.base

import android.content.Context
import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.view.WindowManager
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.asia5b.a5mall.middleware.R
import com.asia5b.a5mall.middleware.utils.LocalManageUtil
import com.asia5b.a5mall.middleware.utils.getEventBus
import com.asia5b.a5mall.middleware.utils.joinComposite
import com.asia5b.a5mall.middleware.widget.refresh.AutoRefreshLayout
import com.jakewharton.rxbinding3.view.clicks
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener
import com.scwang.smartrefresh.layout.listener.OnRefreshListener
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.functions.Consumer
import io.reactivex.schedulers.Schedulers
import org.greenrobot.eventbus.EventBus
import java.util.concurrent.TimeUnit

/**
 * Created by zhangyuncai on 2020/8/19.
 */
abstract class SimpleActivity<VIEWMODEL : SimpleViewModel, DATABINDING : ViewDataBinding> : AppCompatActivity(), OnRefreshListener,
        OnLoadMoreListener, BaseControl {
    val mActivity by lazy { this }
    abstract val viewModelClazz: Class<VIEWMODEL>

    //状态栏文字是否暗色
    open var sIsDark = false
    lateinit var mViewModel: VIEWMODEL
    lateinit var mDataBinding: DATABINDING
    val mCompositeDisposable = CompositeDisposable()
    open val isRegisterEventBus: Boolean = false//是否注册广播
    abstract fun getDataBinding(): DATABINDING

    var loadingDialog: LoadingDialog? = null
    var mSmartRefreshLayout: AutoRefreshLayout? = null
        set(value) {
            field = value
            field?.setOnRefreshListener(this)
            field?.setOnLoadMoreListener(this)
        }
    protected val simpleLifecycleObserver by lazy { SimpleLifecycleObserver() }
    override fun attachBaseContext(newBase: Context) {
        //设置多语言
        super.attachBaseContext(LocalManageUtil.attachBaseContext(newBase))
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        /**执行生命周期监听*/
        lifecycle.addObserver(simpleLifecycleObserver)
        if (isRegisterEventBus) {
            getEventBus().register(this)
        }
        setStatusTrans(sIsDark)
        mDataBinding = getDataBinding()
        setContentView(mDataBinding.root)
        mViewModel = ViewModelProvider(this).get(viewModelClazz)
        mViewModel.loadingLiveData.observe(SimpleActivity@this, Observer {
            when (it) {
                0 -> {
                    showLoadingBar("")
                }
                1 -> {
                    dismissLoadingBar()
                }
                else -> {
                    showLoadingFailureError()
                }
            }
        })


        initView()
        initEvent()
        startObserver()
        initData()
    }

    protected abstract fun initView()
    protected abstract fun initEvent()
    open fun startObserver() {}
    protected abstract fun initData()
    private var isCanShow = false
    fun showLoadingBar(content: String) {
        isCanShow = true
        val subscribe = Observable.timer(500, TimeUnit.MILLISECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(Consumer {
                    if (isCanShow) {
                        if (loadingDialog == null) {
                            loadingDialog = LoadingDialog(this)
                        }
                        if (!loadingDialog!!.isShowing) {
                            loadingDialog?.show()
                        }
                        loadingDialog!!.message = content
                    }
                }, Consumer { })
        subscribe.joinComposite(mCompositeDisposable)
    }

    fun dismissLoadingBar() {
        isCanShow = false
        runOnUiThread {
            loadingDialog?.dismiss()
            mSmartRefreshLayout?.finishRefresh()
            mSmartRefreshLayout?.finishLoadMore()
        }

    }

    //    @UiThread
    fun showLoadingFailureError(throwable: Throwable? = null) {
        dismissLoadingBar()
        throwable?.printStackTrace()
    }

    override fun onRefresh(refreshLayout: RefreshLayout) {

    }

    override fun onLoadMore(refreshLayout: RefreshLayout) {

    }

    /**
     * 防止双击
     *
     * @param v
     */
    fun onFilterDoubleClick(v: View, listener: View.OnClickListener) {
        val subscribe = v.clicks()
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribe { unit -> listener.onClick(v) }
        mCompositeDisposable.add(subscribe)
    }

    /**
     * 点击返回按钮
     *
     * @param v
     */
    open fun backClick(v: View) {
        onBackPressed()
    }


    /**
     * 设置状态栏的字体颜色是否高亮
     * @param dark true:会显示灰色 : false :会显示白色（亮色）
     */
    open fun setAndroidNativeLightStatusBar(dark: Boolean) {
        val decor = window.decorView
        if (dark) {
            decor.systemUiVisibility =
                    View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
        } else {
            decor.systemUiVisibility =
                    View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
        }
    }

    /**
     * 设置全透明状态栏
     * @param isDark 状态栏文字灰色
     */
    open fun setStatusTrans(isDark: Boolean = false) {
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS or WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION)
        if (isDark) {
            window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
        } else {
            window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
        }
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
        window.statusBarColor = Color.TRANSPARENT
    }

    /**
     * @Note   添加callBack
     * @param  listener 监听回调
     */
    override fun addLifeCycleListener(listener: (state: Int) -> Unit) {
        simpleLifecycleObserver.add(listener)
    }


    override fun onDestroy() {
        super.onDestroy()
        loadingDialog?.dismiss()
        /**执行生命周期监听*/
        lifecycle.removeObserver(simpleLifecycleObserver)
        if (isRegisterEventBus) {
            getEventBus().unregister(this)
        }
        mCompositeDisposable.dispose()
    }
}